<template>
  <div class="list">
    <el-table v-loading="loading" :data="houseList" @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="50" align="center" /> -->
      <el-table-column label="房间" align="center" key="roomNumber" prop="roomNumber" v-if="columns[0].visible">
      <template slot-scope="scope">
        <span>{{ generateRoom(scope.row) }}</span>
      </template>
      </el-table-column>
      <el-table-column label="楼盘" align="center" key="estateName" prop="estateName" v-if="columns[1].visible"
        :show-overflow-tooltip="true" />
      <el-table-column label="承租/预定信息" align="center" key="" prop="" v-if="columns[2].visible"
        :show-overflow-tooltip="true" />
      <el-table-column label="租金" align="center" key="deptName" prop="dept.deptName" v-if="columns[3].visible"
        :show-overflow-tooltip="true" />
      <el-table-column label="户型" align="center" key="phonenumber" prop="phonenumber" v-if="columns[4].visible"
        width="120" />
      <el-table-column label="是否线上出租" align="center" key="houseState" v-if="columns[5].visible">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.dict_house_state" :value="scope.row.houseState" />
        </template>
      </el-table-column>
      <el-table-column label="是否线上出租" align="center" key="onlineRentalType" v-if="columns[6].visible">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.dict_online_rental_type" :value="scope.row.onlineRentalType" />
        </template>
      </el-table-column>
      <el-table-column label="承租人" align="center" key="onlineRentalType" v-if="columns[7].visible">
        <template slot-scope="scope">
          
        </template>
      </el-table-column>
      <el-table-column label="房屋类型" align="center" key="houseType" prop="houseType" v-if="columns[8].visible">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.dict_house_type" :value="scope.row.houseType" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" v-if="columns[6].visible" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
        <template slot-scope="scope" v-if="scope.row.userId !== 1">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:user:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:user:remove']">删除</el-button>
          <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)"
            v-hasPermi="['system:user:resetPwd', 'system:user:edit']">
            <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="handleResetPwd" icon="el-icon-key"
                v-hasPermi="['system:user:resetPwd']">重置密码</el-dropdown-item>
              <el-dropdown-item command="handleAuthRole" icon="el-icon-circle-check"
                v-hasPermi="['system:user:edit']">分配角色</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
  </div>
</template>

<script>
import {
  getUser,
  delUser,
  addUser,
  updateUser,
  resetUserPwd,
  changeUserStatus,
} from "@/api/system/user";
import { listFindHouse } from '@/api/house/condition'
export default {
  props: {
    queryParams: {
      default: {},
    },
  },
  dicts: ["dict_online_rental_type", "dict_house_state",'dict_house_type'],
  data() {
    return {
      // 遮罩层
      loading: false,
      // 总条数
      total: 0,
      // 房屋表格数据
      houseList: null,
      // 查询参数
      //   queryParams: {
      //     pageNum: 1,
      //     pageSize: 10,
      //     userName: undefined,
      //     phonenumber: undefined,
      //     status: undefined,
      //     deptId: undefined,
      //   },
      // 列信息
      columns: [
        { key: 0, label: `房间`, visible: true },
        { key: 1, label: `楼盘`, visible: true },
        { key: 2, label: `承租/预定信息`, visible: true },
        { key: 3, label: `租金`, visible: true },
        { key: 4, label: `户型`, visible: true },
        { key: 5, label: `状态`, visible: true },
        { key: 6, label: `是否线上出租`, visible: true },
        { key: 7, label: `承租人`, visible: true },
        { key: 8, label: `房屋类型`, visible: true },
      ],
      diy: {
        "total": 10,
        "rows": [
          {
            "createBy": "1",
            "createTime": "2023-10-26 14:10:52",
            "updateBy": "",
            "operatorId": 1,
            "updateTime": null,
            "remark": null,
            "houseId": "H16983006519101852",
            "roomNumber": "11",
            "estateId": 7,
            "estateName": "希望楼盘",
            "buildingId": 10,
            "buildingName": "A",
            "orgId": null,
            "houseNature": "1",
            "houseType": "1",
            "houseState": "1",
            "houseLeaseState": "1",
            "houseMaintainState": "1",
            "onlineRentalType": "1",
            "shareFlatType": null,
            "houseArea": 32,
            "roomType": null,
            "houseOrientation": null,
            "housePropertyType": null,
            "housePropertyOwner": null,
            "smartFurnitureType": null,
            "waterMeterNumber": null,
            "electricMeterNumber": null,
            "gasMeterNumber": null,
            "houseManagerId": null,
            "houseManagerName": null,
            "houseManagerPhone": null,
            "propertyId": null,
            "propertyName": null,
            "houseQrCode": null,
            "provinceId": null,
            "provinceName": null,
            "cityId": null,
            "cityName": null,
            "districtId": null,
            "districtName": null,
            "streetId": null,
            "streetName": null,
            "communityId": null,
            "premisesAddress": null,
            "delFlag": null,
            "unitId": 2,
            "unitName": "2",
            "floors": 2,
            "subordinateHouseList": null,
            "totalHouseNumber": null,
            "rentalHouseNumber": null,
            "vacancyHouseNumber": null,
            "vacancyHousePercentage": null,
            "onlineDownHouseNumber": null,
            "onlineDownRentalHouseNumber": null,
            "onlineUpHouseNumber": null,
            "onlineUpRentalHouseNumber": null,
            "startCreateTime": null,
            "endCreateTime": null,
            "housingAllocation": null,
            "facilitiesItemList": null,
            "estate": {
              "createBy": "",
              "createTime": null,
              "updateBy": "",
              "operatorId": null,
              "updateTime": "2023-10-24 18:21:48",
              "remark": null,
              "estateId": "7",
              "estateType": "1",
              "estateName": "希望楼盘",
              "provinceId": 111,
              "cityId": 22,
              "districtId": 33,
              "streetId": 44,
              "communityId": 55,
              "premisesAddress": "希望路",
              "propertyId": null,
              "propertyName": null,
              "longitude": null,
              "latitude": null,
              "delFlag": null,
              "buildingList": null,
              "estateNumber": null,
              "buildingNumber": null,
              "unitNumber": null,
              "houseNumber": null
            },
            "estateJson": null,
            "building": {
              "createBy": "",
              "createTime": "2023-10-19 14:00:33",
              "updateBy": "",
              "operatorId": null,
              "updateTime": "2023-10-24 18:24:31",
              "remark": null,
              "buildingId": "10",
              "estateId": "7",
              "buildingName": "A",
              "delFlag": null,
              "buildingNumber": null,
              "unitNumber": null,
              "houseNumber": null,
              "estateType": null,
              "estateName": "希望楼盘",
              "provinceId": null,
              "cityId": null,
              "districtId": null,
              "streetId": null,
              "communityId": null,
              "premisesAddress": null,
              "propertyId": null,
              "propertyName": null,
              "unitList": null,
              "vacancyRate": null
            },
            "buildingJson": null,
            "unit": {
              "createBy": "",
              "createTime": null,
              "updateBy": "",
              "operatorId": null,
              "updateTime": null,
              "remark": null,
              "unitId": "2",
              "buildingId": "10",
              "unitName": "1",
              "floors": 11,
              "houseNumber": 2,
              "delFlag": null,
              "listMap": null
            },
            "unitJson": null,
            "estateType": null
          }
        ],
        "code": 200,
        "msg": "查询成功"
      }
    };
  },
  computed:{
    generateRoom() {
      return (row) => {
        let name = "";
        if (row.buildingName) name += row.buildingName + "栋";
        if (row.unitName) name += row.unitName + "单元";
        if (row.roomNumber) name += row.roomNumber + "号";
        return name;
      };
    },
  },
  created() {
    this.getList();
    // this.houseList = this.diy.rows;
    // this.total = this.diy.total;
    this.loading = false;
  },
  methods: {
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      listFindHouse(this.queryParams).then(
        (response) => {
          this.houseList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      )
    },
    //获取房源树结构
    getBuildingsTree() {
      //start 接口获取
      //end
      this.buildingsOptions = buildingTree;
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.handleQuery();
    },
    // 用户状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$modal
        .confirm('确认要"' + text + '""' + row.userName + '"用户吗？')
        .then(function () {
          return changeUserStatus(row.userId, row.status);
        })
        .then(() => {
          this.$modal.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.status = row.status === "0" ? "1" : "0";
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        userId: undefined,
        deptId: undefined,
        userName: undefined,
        nickName: undefined,
        password: undefined,
        phonenumber: undefined,
        email: undefined,
        sex: undefined,
        status: "0",
        remark: undefined,
        postIds: [],
        roleIds: [],
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.queryParams.deptId = undefined;
      this.$refs.tree.setCurrentKey(null);
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.userId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleResetPwd":
          this.handleResetPwd(row);
          break;
        case "handleAuthRole":
          this.handleAuthRole(row);
          break;
        default:
          break;
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      getUser().then((response) => {
        this.postOptions = response.posts;
        this.roleOptions = response.roles;
        this.open = true;
        this.title = "添加用户";
        this.form.password = this.initPassword;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const userId = row.userId || this.ids;
      getUser(userId).then((response) => {
        this.form = response.data;
        this.postOptions = response.posts;
        this.roleOptions = response.roles;
        this.$set(this.form, "postIds", response.postIds);
        this.$set(this.form, "roleIds", response.roleIds);
        this.open = true;
        this.title = "修改用户";
        this.form.password = "";
      });
    },
    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      this.$prompt('请输入"' + row.userName + '"的新密码', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        inputPattern: /^.{5,20}$/,
        inputErrorMessage: "用户密码长度必须介于 5 和 20 之间",
      })
        .then(({ value }) => {
          resetUserPwd(row.userId, value).then((response) => {
            this.$modal.msgSuccess("修改成功，新密码是：" + value);
          });
        })
        .catch(() => { });
    },
    /** 分配角色操作 */
    handleAuthRole: function (row) {
      const userId = row.userId;
      this.$router.push("/system/user-auth/role/" + userId);
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.userId != undefined) {
            updateUser(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addUser(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.userId || this.ids;
      this.$modal
        .confirm('是否确认删除用户编号为"' + userIds + '"的数据项？')
        .then(function () {
          return delUser(userIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/user/export",
        {
          ...this.queryParams,
        },
        `user_${new Date().getTime()}.xlsx`
      );
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(
        "system/user/importTemplate",
        {},
        `user_template_${new Date().getTime()}.xlsx`
      );
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
        response.msg +
        "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
  },
};
</script>

<style lang="scss" scoped>
.list {
  margin-top: 30px;
}
</style>
